<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Addyourproperty extends MX_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 * 	- or -
	 * 		http://example.com/index.php/welcome/index
	 * 	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function Addyourproperty() {
		parent::__construct();
		$this->load->model('lookupmodel');
		$this->load->model('helpermodel');
		$this->load->model('mdl_addyourproperty');
		$this->load->model('email/emailmodel');
		//check is logged in
		$this->load->model('languagemodel');
		$this->language = $this->languagemodel->is_language_using();
		$this->load->helper('MY_url_helper');
		$this->load->helper('text');
		
		//right side banner
		$this->load->model('banners/bannermodel');
	}

	public function index() {
		$this->lang->load('addyourproperty/addyourproperty', $this->language);

		//SEO
		$data['title'] = $this->lang->line('addyourproperty_text_title');
		$data['description'] = $this->lang->line('addyourproperty_text_description');
		$data['keywords'] = $this->lang->line('addyourproperty_text_keywords');

		//Text
		$data['text_heading'] = $this->lang->line('text_heading');

		$data['breadcrumbs'][] = array(
			'text'      => 'Home',
			'href'      => base_url()
		);

		$data['breadcrumbs'][] = array(
			'text'      => $this->lang->line('text_heading'),
			'href'      => base_url() . 'addyourproperty'
			);

			$data['dd_propertytype'] = $this->lookupmodel->GetPropertyType($this->config->item('config_language_id'), $this->config->item('market'));
			$data['dd_propertycategory'] = $this->lookupmodel->GetPropertyCategory($this->config->item('config_language_id'), $this->config->item('market'));

			//attachments array to hold images
			$attachments = array();

			//set all three images to NULL
			$img1 = $img2 = $img3 = NULL;

			//form id is 1 for postproperty form
			$admin_email_obj = $this->emailmodel->get_admin_email(1);

			//get admin email
			$admin_email = $admin_email_obj->AdminAddress;

			if(isset($_POST['action']) && $_POST['action']=="sendenquiry"){
				//collect data from post property form
				$dataObj['PropertyFor'] = $this->input->post('propertyfor');
				$dataObj['StatusFID'] = 3; //Pending status and waiting for an approval
				$dataObj['CountryFID'] = $this->lookupmodel->getCountryId($this->config->item('market')); //Default Indonesia Country
				$dataObj['CityFID'] = $this->input->post('city');
				$dataObj['LocationFID'] = 0;
				$dataObj['SubAreaFID'] = 0;
				$dataObj['StreetFID'] = NULL;
				$dataObj['PrjDirectoryFID'] = NULL;
				$dataObj['PropertyTypeFID'] = $this->input->post('propertytype');
				$dataObj['PropertyClass'] = 'strata'; //Add Property Calss to Form
				$dataObj['Size_Min'] = $this->input->post('area');
				$dataObj['SizeUnit'] = $this->input->post('areaunit');
				$dataObj['Price_Min'] = $this->input->post('price');
				$dataObj['PriceUnit'] = $this->input->post('priceunit');
				$dataObj['NewLaunch'] = 0; //Set to default value
				$dataObj['ListingType'] = 'resale'; //Set to default value;
				$dataObj['Longitude'] = $this->input->post('longitude');
				$dataObj['Latitude'] = $this->input->post('latitude');
				$dataObj['Bedroom'] = $this->input->post('bedroom');
				$dataObj['Bathroom'] = $this->input->post('bathroom');
				$dataObj['CreatedDate'] = date("Y-m-d H:i:s");
				$dataObj['MarketFID'] = $this->config->item('market');
					
				//Firstly implement inserting post listing data to Listing table
				$ListingId = $this->mdl_addyourproperty->_insert($dataObj);
					
				if($ListingId > 0) {
					$languages = $this->lookupmodel->getLanguages($this->config->item('market'));
					foreach ($languages as $lan) {
						//Description table
						
						$dataDesObj['ListingFID'] = $ListingId;
						$dataDesObj['LanguageFID'] = $lan->Language_ID;
						$dataDesObj['City'] = $this->input->post('city_value');
						if($this->input->post('locality_value') != "All") {
							$dataDesObj['Location'] = $this->input->post('locality_value');
						} else {
							$dataDesObj['Location'] = NULL;
						}
	
						if($this->input->post('district_value') != "All") {
							$dataDesObj['Subarea'] = $this->input->post('district_value');
						} else {
								
						}
						$dataDesObj['ProjectName'] = $this->input->post('projectname');
						$dataDesObj['PropertyType'] = $this->input->post('property_value');
						$dataDesObj['Description'] = $this->input->post('keyfeatures');
						//Secondly insert data to Listing Description table
						
						$ListingDesId = $this->mdl_addyourproperty->_insertToListingDes($dataDesObj);
					}
					

					//Thirdly insert data to Listing Media Table
					//process uploading image 1
					if (!empty($_FILES['image1']['name'])){

						$config['upload_path'] = HTTP_POST_LISTING_IMAGE;
						$config['allowed_types'] = 'gif|jpg|png';
						$config['max_size']	= '2048';
						$config['max_width']  = '1024';
						$config['max_height']  = '1024';
						$config['overwrite']  = FALSE;
							
						$this->load->library('upload', $config);

						$this->upload->file_name = '';//insert this line
						if (!$this->upload->do_upload('image1'))
						{
							//display area
							$data['error'] = array('error' => $this->upload->display_errors());
						}
						else
						{
							$img1_data = $this->upload->data();

							$img1 = $img1_data['file_name'];

							$attachment['source'] = $img1_data["full_path"];
							$attachment['filename'] = $img1_data["file_name"];

							array_push($attachments, $attachment);

							$dataImg = $this->prepareImageDBString($img1_data["full_path"]);
							//$dataImg = base64_encode($dataImg);

							$dataListingMedia['ListingFID'] = $ListingId;
							$dataListingMedia['MediaType'] = 'Gallery';
							$dataListingMedia['FileName'] = $this->get_file_name($img1_data["file_name"]);
							$dataListingMedia['FileExtension'] = $img1_data['file_ext'];
							$dataListingMedia['FileData'] = $dataImg;
							$dataListingMedia['IsActive'] = 0;
							$dataListingMedia['SortOrder'] = NULL;

							$result = $this->mdl_addyourproperty->_insertToListingMedia($dataListingMedia);
						}
					}

					//process uploading image 2
					if (!empty($_FILES['image2']['name'])){
						$config['upload_path'] = HTTP_POST_LISTING_IMAGE;
						$config['allowed_types'] = 'gif|jpg|png';
						$config['max_size']	= '2048';
						$config['max_width']  = '1024';
						$config['max_height']  = '1024';
						$config['overwrite']  = FALSE;
							
						$this->load->library('upload', $config);

						$this->upload->file_name = '';//insert this line
						//process image 2
						if ( ! $this->upload->do_upload('image2'))
						{
							//display area
							$data['error'] = array('error' => $this->upload->display_errors());
						}
						else
						{

							$img2_data = $this->upload->data();
							$img2 = $img2_data['file_name'];
								
							$attachment['source'] = $img2_data["full_path"];
							$attachment['filename'] = $img2_data["file_name"];

							array_push($attachments, $attachment);

							$dataImg = $this->prepareImageDBString($img2_data["full_path"]);
							//$dataImg = base64_encode($dataImg);

							$dataListingMedia['ListingFID'] = $ListingId;
							$dataListingMedia['MediaType'] = 'Gallery';
							$dataListingMedia['FileName'] = $this->get_file_name($img2_data["file_name"]);
							$dataListingMedia['FileExtension'] = $img2_data['file_ext'];
							$dataListingMedia['FileData'] = $dataImg;
							$dataListingMedia['IsActive'] = 0;
							$dataListingMedia['SortOrder'] = NULL;

							$result = $this->mdl_addyourproperty->_insertToListingMedia($dataListingMedia);
						}
					}

					//process uploading image3
					if (!empty($_FILES['image3']['name'])){
							
						$config['upload_path'] = HTTP_POST_LISTING_IMAGE;
						$config['allowed_types'] = 'gif|jpg|png';
						$config['max_size']	= '2048';
						$config['max_width']  = '1024';
						$config['max_height']  = '1024';
						$config['overwrite']  = FALSE;
							
						$this->load->library('upload', $config);

						$this->upload->file_name = '';//insert this line
						//process image 3
						if ( ! $this->upload->do_upload('image3'))
						{
							//display area
							$data['error'] = array('error' => $this->upload->display_errors());
						}
						else
						{
							$img3_data = $this->upload->data();
							$img3 = $img3_data['file_name'];

							$attachment['source'] = $img3_data["full_path"];
							$attachment['filename'] = $img3_data["file_name"];

							array_push($attachments, $attachment);

							$dataImg = $this->prepareImageDBString($img3_data["full_path"]);
							//$dataImg = base64_encode($dataImg);

							$dataListingMedia['ListingFID'] = $ListingId;
							$dataListingMedia['MediaType'] = 'Gallery';
							$dataListingMedia['FileName'] = $this->get_file_name($img3_data["file_name"]);
							$dataListingMedia['FileExtension'] = $img3_data['file_ext'];
							$dataListingMedia['FileData'] = $dataImg;
							$dataListingMedia['IsActive'] = 0;
							$dataListingMedia['SortOrder'] = NULL;

							$result = $this->mdl_addyourproperty->_insertToListingMedia($dataListingMedia);
						}
					}

					//Member table
					$dataMemObj['FirstName'] = $this->input->post('name');
					$dataMemObj['Mobile'] = $this->input->post('mobile');
					$dataMemObj['Email'] = $this->input->post('email');
					$dataMemObj['IsApproved'] = 0;
					$dataMemObj['CreatedDate'] = date("Y-m-d H:i:s");
					$dataMemObj['MemberGroupFID'] = 3; //Set default to Posting Listing
					$dataMemObj['MarketFID'] = $this->config->item('market');;

					$ListingId = $this->mdl_addyourproperty->_insertToMember($dataMemObj);
				} else {
					redirect(base_url() . 'error_404', 'refresh');
				}
					
				$data['propertyfor_value'] = $this->input->post('propertyfor_value');
				$data['propertytype_value'] = $this->input->post('propertytype_value');
				$data['city_value'] = $this->input->post('city_value');
				$data['locality_value'] = $this->input->post('locality_value');
				$data['district_value'] = $this->input->post('district_value');
				$data['priceunit_value'] = $this->input->post('priceunit_value');
				$data['tenure_value'] = $this->input->post('tenure_value');
				$data['datecreated'] = date('d-M-y G:i:s');
					
				//set and send email to admin
				$to = $admin_email;
					
				$from = "Jone Lang LaSalle Residential Indonesia";
				$bcc = "";
				$subject = "[New Post Property submission] Jones Lang LaSalle Residential - From " . $dataMemObj['FirstName'];
					
				$text = "The following Property is submitted by " . $dataMemObj['FirstName'] . "\n\n";
				$text .= "Personal Particulars:\n ---------------------\n";
					
				$text .= "Name: " . $dataMemObj['FirstName'] . "\n";
				$text .= "Mobile: " . $dataMemObj['Mobile'] . "\n";
				$text .= "Email: " . $dataMemObj['Email'] . "\n\n";
				$text .= "Property Information: \n -----------------\n\n";
				$text .= "Property For: " . $data['propertyfor_value'] . "\n";
				$text .= "Property Type: " . $data['propertytype_value'] . "\n";
				$text .= "Project Name: " . $dataDesObj['ProjectName'] . "\n";
					
				if (!empty($data['city_value'])) {
					$text .= "City: " . $data['city_value'] . "\n";
				}
					
				if (!empty($data['locality_value']) && $data['locality_value'] != 'All') {
					$text .= "Location: " . $data['locality_value'] . "\n";
				}
					
				if (!empty($data['district_value']) && $data['district_value'] != 'All') {
					$text .= "Sub area: " . $data['district_value'] . "\n";
				}
					
				$text .= "Price: " . $dataObj['Price_Min'] . ' ' . $data['priceunit_value'] . "\n";
					
				$text .= "Area: " . $dataObj['Size_Min'] . ' ' . $dataObj['SizeUnit'] . "\n";
					
					
				if ($data['tenure_value'] != "" && !is_null($data['tenure_value'])) {
					$text .= "Tenure: " . $data['tenure_value'] . "\n";
				}
					
					
				$text .= "Bedroom: " . $dataObj['Bedroom'] . "\n";
				$text .= "Bathroom: " . $dataObj['Bathroom'] . "\n";
				$text .= "Key Features:\n " . $dataDesObj['Description'] . "\n\n";
				$text .= "This message is generated and sent via JLL Residential Portal, Post Property feature. Please do not reply to this email.";
					
					
					
				$message = "The following Property is submitted by " . $dataMemObj['FirstName'] . "<br/><br/>";
				$message .= "Personal Particulars:<br/> ---------------------<br/>";
					
				$message .= "Name: " . $dataMemObj['FirstName'] . "<br/>";
				$message .= "Mobile: " . $dataMemObj['Mobile'] . "<br/>";
				$message .= "Email: " . $dataMemObj['Email'] . "<br/><br/>";
				$message .= "Property Information: <br/> -----------------<br/><br/>";
				$message .= "Property For: " . $data['propertyfor_value'] . "<br/>";
				$message .= "Property Type: " . $data['propertytype_value'] . "<br/>";
				$message .= "Project Name: " . $dataDesObj['ProjectName'] . "<br/>";
					
				if (!empty($data['city_value'])) {
					$message .= "City: " . $data['city_value'] . "<br/>";
				}
					
				if (!empty($data['locality_value']) && $data['locality_value'] != 'All') {
					$message .= "Location: " . $data['locality_value'] . "<br/>";
				}
					
				if (!empty($data['district_value']) && $data['district_value'] != 'All') {
					$message .= "Sub area: " . $data['district_value'] . "<br/>";
				}

				$message .= "Price: " . $dataObj['Price_Min'] . ' ' . $data['priceunit_value'] . "<br/>";
				$message .= "Area: " . $dataObj['Size_Min'] . ' ' . $dataObj['SizeUnit'] . "<br/>";
					
				if ($data['tenure_value'] != "" && !is_null($data['tenure_value'])) {
					$message .= "Tenure: " . $data['tenure_value'] . "<br/>";
				}
					
				$message .= "Bedroom: " . $dataObj['Bedroom'] . "<br/>";
				$message .= "Bathroom: " . $dataObj['Bathroom'] . "<br/>";
				$message .= "Key Features:<br/> " . $dataDesObj['Description'] . "<br/><br/>";
				$message .= "This message is generated and sent via JLL Residential Portal, Post Property feature. Please do not reply to this email.";
					
				$success = $this->emailmodel->sendmail_wth_attachments($to, $from, $bcc, $subject, $message, $text, $attachments);
				//$success === true;
					
				if ($success === true) {
					redirect(base_url() . 'addyourproperty/success', 'location'); exit();
				}
			}

			$data['success'] = "";
			$data['module'] = "addyourproperty";
			$data['view_file'] = "addyourproperty";

			echo Modules::run('template/default_template', $data);
	}

	function success() {
		$this->lang->load('addyourproperty/addyourproperty', $this->language);

		//SEO
		$data['title'] = $this->lang->line('addyourproperty_text_title');
		$data['description'] = $this->lang->line('addyourproperty_text_description');
		$data['keywords'] = $this->lang->line('addyourproperty_text_keywords');

		//Text
		$data['text_heading'] = $this->lang->line('text_heading');

		$data['module'] = "addyourproperty";
		$data['view_file'] = "addyourproperty";

		$data['breadcrumbs'][] = array(
			'text'      => 'Home',
			'href'      => base_url()
		);

		$data['breadcrumbs'][] = array(
			'text'      => $this->lang->line('text_homeloan'),
			'href'      => base_url() . 'addyourproperty.html'
			);

			$data['breadcrumbs'][] = array(
			'text'      => $this->lang->line('heading_title'),
			'href'      => base_url() . 'addyourproperty/success'
			);

			$data['success'] = $this->uri->segment(2);

			echo Modules::run('template/default_template', $data);
	}
	
	function prepareImageDBString2($filepath)
	{
		$data_string = 'null';
		
		$dataString = file_get_contents($data['full_path']);
      	$arrData = unpack("H*hex", $dataString);
       	$data_string = "0x".$arrData['hex'];
       	
       	return $data_string;
	}

	function prepareImageDBString($filepath)
	{
		$out = 'null';
		$handle = @fopen($filepath, 'rb');
		if ($handle)
		{
			$content = @fread($handle, filesize($filepath));
			//$content = bin2hex($content);
			//$content = $content;
			//$content = hexdec($content);
           	
           	$arrData = unpack("H*hex", $content);
            $content = $arrData['hex'];
			
			@fclose($handle);
			$out = "0x".$content;
		}
	  
		return $out;
	}

	function get_extension($filename) {
		$x = explode('.', $filename);
		return '.'.end($x);
	}

	function get_file_name($filename) {
		$x = explode('.', $filename);
		return current($x);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */